# _*_ coding:utf-8 _*_
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.views.generic.base import View
from django.shortcuts import render
from home.forms import UploadImageForm
from .models import UserProfile
from forms import PersonalForm
from django.contrib.auth.hashers import make_password, check_password
from django.contrib.auth import authenticate, login, logout

# Create your views here.


class UploadImageView(LoginRequiredMixin, View):
    login_url = '/login/'
    redirect_field_name = 'next'

    def post(self, request):
        # 用户上传的文件保存到imageform，为modelform添加instance值直接保存
        image_form = UploadImageForm(
            request.POST, request.FILES, instance=request.user)
        if image_form.is_valid():
            image_form.save()
            # 取出cleaned data中的值,一个dict
            # image = image_form.cleaned_data['image']
            # request.user.image = image
            # request.user.save()
            return HttpResponse(
                '{"status":"success"}',
                content_type='application/json')
        else:
            return HttpResponse(
                '{"status":"fail"}',
                content_type='application/json')


class ModifyUserInfoView(View):
    def get(self, request):
        return render(request, "ModifyUserinfo.html")

    def post(self, request):
        personal_form = PersonalForm(request.POST)
        if personal_form.is_valid():
            user_name = request.POST.get("username_per", "")
            if request.user.is_authenticated():
                nick_name = request.POST.get('nickname', '')
                gen_der = request.POST.get('gender', '')
                mob_ile = request.POST.get('mobile', '')
                add_res = request.POST.get('address', '')

                # 用户绑定Trading
                broker_id = request.POST.get('brokerid', '')
                user_id = request.POST.get('userid', '')
                paasword_trader = request.POST.get('paaswordtrader', '')

                # 用户信息更新
                all_Personal = UserProfile.objects.get(username=user_name)
                all_Personal.nick_name = nick_name
                all_Personal.address = add_res
                all_Personal.gender = gen_der
                all_Personal.mobile = mob_ile
                all_Personal.brokerID = broker_id
                all_Personal.userID = user_id
                all_Personal.password_trader = paasword_trader
                all_Personal.save()

            return render(request, "ModifyUserinfo.html", {"msg": "信息更新成功！！", "num": "true"})
        else:
            return render(request, "login.html", {"msg": "用户名或密码不正确", "num": "false"})


class kMapView(View):
    def get(self, request):
        return render(request, "kmap.html")

    def post(self, request):
        return render(request, "kmap.html")
